var express = require("express");

var url = require("url");

var web = express();

var fs = require("fs");

var bodyParser = require("body-parser");

var post = require("./post");
var qs = require('querystring');


web.post("/login", function(request, response) {
    response.header("Access-Control-Allow-Origin", "*");
    var postData = "";
    /**
     * 因为post方式的数据不太一样可能很庞大复杂，
     * 所以要添加监听来获取传递的数据
     * 也可写作 req.on("data",function(data){});
     */
    request.addListener("data", function(data) {
        postData += data;
    });
    /**
     * 这个是如果数据读取完毕就会执行的监听方法
     */
    request.addListener("end", function() {
        var query = qs.parse(postData);
        console.log(query) //内容
            // writeOut(query, res);
        fs.readFile(query.username + ".txt", "utf8", function(err, data) {
            if (err) {
                response.write("用户名不存在");
                response.end();
            } else {
                response.write("恭喜你登录成功");
                response.end();
            }
        })
    });
});

web.post("/regist", function(request, response) {
    response.header("Access-Control-Allow-Origin", "*");
    var postData = "";
    /**
     * 因为post方式的数据不太一样可能很庞大复杂，
     * 所以要添加监听来获取传递的数据
     * 也可写作 req.on("data",function(data){});
     */
    request.addListener("data", function(data) {
        postData += data;
    });
    /**
     * 这个是如果数据读取完毕就会执行的监听方法
     */
    request.addListener("end", function() {
        var query = qs.parse(postData);
        console.log(query) //内容
            // writeOut(query, res);
        fs.readFile(query.username + ".txt", "utf8", function(err, data) {
            if (err) {
                fs.writeFile(query.username + ".txt", JSON.stringify(query), function(err) {
                    response.write('注册成功');
                    response.end();
                });
            } else {
                response.write("账号已存在");
                response.end();
            }
        })
    });
});


web.listen(8000, function() {
    console.log("success");
});